package com.sanpu.kxe.business.trade.view;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseTitleActivity;
import com.sanpu.kxe.business.card.bean.BankInfoOutput;
import com.sanpu.kxe.business.card.provider.ICardProvider;
import com.sanpu.kxe.business.trade.adapter.ChooseBankAdapter;
import com.sanpu.kxe.business.trade.adapter.ChoosePayAdapter;
import com.sanpu.kxe.business.trade.bean.PayCollectionOutput;
import com.sanpu.kxe.business.trade.contract.PersonalGatheringContract;
import com.sanpu.kxe.business.trade.contract.TradeConfig;
import com.sanpu.kxe.business.trade.interfaces.IComfirmClickListener;
import com.sanpu.kxe.business.trade.presenter.PersonalGatheringPresenter;
import com.sanpu.kxe.common.interfaces.DialogViewListener;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.jump.eventbus.RefreshBankEvent;
import com.sanpu.kxe.jump.imageloader.JKImageLoader;
import com.sanpu.kxe.module.dialog.GatherComfirmDialog;
import com.sanpu.kxe.module.roundview.RoundTextView;
import com.sanpu.kxe.module.widget.EditTextWithDel;
import com.sanpu.kxe.utils.DialogUtil;
import com.sanpu.kxe.utils.PublicProviderUtil;
import com.sanpu.kxe.utils.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Description：个人收款
 * Created by 薛勇军 on 2019/9/25.
 */
@Route(path = "/trade/PersonalGathering")
public class PersonalGatheringActivity extends BaseTitleActivity implements PersonalGatheringContract.View {

    @Bind(R.id.gatherListView)
    ListView gatherListView;
    @Bind(R.id.comfirmRtv)
    RoundTextView comfirmRtv;

    private EditTextWithDel gatheringMoneyEt;

    private ImageView vInIcon, vOutIcon;

    private TextView vOutBankName, vInBankName;

    private LinearLayout vOutSelectBank, vInSelectBank;

    private ChooseBankAdapter mBankAdapter;

    private ChoosePayAdapter mPayAdapter;

    private GatherComfirmDialog vComfirmDialog;

    private PersonalGatheringContract.Presenter mPresenter;

    private ArrayList<BankInfoOutput> mOutBankList = new ArrayList<>();
    private ArrayList<BankInfoOutput> mInBankList = new ArrayList<>();
    private List<PayCollectionOutput> mPayListDatas = new ArrayList<>();
    private PayCollectionOutput mCurrentCollection;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_personal_gathering;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setTitle("收款");

        View headView = LayoutInflater.from(mContext).inflate(R.layout.view_personal_gathering_head, null);
        gatheringMoneyEt = ButterKnife.findById(headView, R.id.gatheringMoneyEt);
        vInIcon = ButterKnife.findById(headView, R.id.in_icon);
        vOutIcon = ButterKnife.findById(headView, R.id.out_icon);
        vOutBankName = ButterKnife.findById(headView, R.id.out_bank_name);
        vInBankName = ButterKnife.findById(headView, R.id.in_bank_name);
        vOutSelectBank = ButterKnife.findById(headView, R.id.out_select_bank);
        vInSelectBank = ButterKnife.findById(headView, R.id.in_select_bank);
        gatherListView.addHeaderView(headView);

        mBankAdapter = new ChooseBankAdapter(mContext, new ArrayList<BankInfoOutput>());

        mPayAdapter = new ChoosePayAdapter(null, mContext);
        gatherListView.setAdapter(mPayAdapter);

        mPresenter = new PersonalGatheringPresenter(this);
        mPresenter.selectUrmBankPage();
        mPresenter.collectionList(TradeConfig.RECEIVABLESTYPE_PERSON);
    }

    @Override
    protected void setListener() {
        super.setListener();
        gatherListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mPayListDatas != null && position > 0) {
                    for (int index = 0; index < mPayListDatas.size(); index++) {
                        if (index == position - 1) {
                            mPayListDatas.get(index).setChoose(true);
                            mCurrentCollection = mPayListDatas.get(index);
                        } else {
                            mPayListDatas.get(index).setChoose(false);
                        }
                    }
                }
                mPayAdapter.setNotifyData(mPayListDatas);
            }
        });
        comfirmRtv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onComfirmClick();
            }
        });
        vOutSelectBank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBankAdapter.setCheckPosition(
                        vOutBankName.getTag() != null ? mOutBankList.lastIndexOf(vOutBankName.getTag()) : -1);
                mBankAdapter.setNotifyData(mOutBankList);
                bankDialog(true);
            }
        });
        vInSelectBank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.getInstance().dialogNoTitletTwoBtnHaveCallBack(mContext,
                        "变更收款卡须更改默认结算卡", "取消", "去更改",
                        new DialogViewListener() {
                            @Override
                            public void btnRightConfirm() {
                                ICardProvider provider = PublicProviderUtil.getProvider(ICardProvider.class);
                                if (provider != null) {
                                    provider.openMyBankListActivity(mContext);
                                }
                            }

                            @Override
                            public void btnLeftCancel() {

                            }
                        });
            }
        });
    }

    /**
     * 点击确认
     */
    private void onComfirmClick() {
        String inputText = gatheringMoneyEt.getText().toString();
        if (TextUtils.isEmpty(inputText)) {
            ToastUtil.showTextViewPrompt("请输入收款金额");
            return;
        }
        if (new BigDecimal(inputText).compareTo(new BigDecimal(1000000)) == 1) {
            ToastUtil.showTextViewPrompt("当前最大输入金额为1000000元");
            gatheringMoneyEt.setText("1000000.00");
            return;
        }
        if (!mPresenter.checkInputMoney(inputText)) return;
        if (vOutBankName.getTag() == null) {
            ToastUtil.showTextViewPrompt("请选择付款信用卡");
            return;
        }
        if (vInBankName.getTag() == null) {
            ToastUtil.showTextViewPrompt("请选择收款储蓄卡");
            return;
        }
        if (mCurrentCollection == null) {
            ToastUtil.showTextViewPrompt("请选择收款通道");
            return;
        } else if (!mPresenter.checkCollectionPay(mCurrentCollection, inputText)) {
            return;
        }
        if (TextUtils.equals("T1", mCurrentCollection.getSettleType())) {//T1
            String remark = "您收款的资金将在下一个工作日转入您的结算卡中（节假日不到账），若需要实时到账，请选择【秒刷秒到】";
            DialogUtil.getInstance().dialogExistTitleTwoBtnHaveCallBack(
                    mContext, "温馨提示", remark, "重新收款", "继续收款",
                    new DialogViewListener() {
                        @Override
                        public void btnRightConfirm() {
                            showComfirmDialog();
                        }

                        @Override
                        public void btnLeftCancel() {

                        }
                    });
            return;
        }
        showComfirmDialog();
    }

    /**
     * 显示收款确认弹框
     */
    private void showComfirmDialog() {
        double txFee = mPresenter.getGatherFee(mCurrentCollection, gatheringMoneyEt.getText().toString());
        vComfirmDialog = null;
        vComfirmDialog = new GatherComfirmDialog(
                mContext, (BankInfoOutput) vOutBankName.getTag(), (BankInfoOutput) vInBankName.getTag(),
                gatheringMoneyEt.getText().toString(), txFee);
        vComfirmDialog.setListener(new IComfirmClickListener() {
            @Override
            public void onComfirmClick() {
                mPresenter.onComfirmPay(((BankInfoOutput) vOutBankName.getTag()).getBankId(),
                        ((BankInfoOutput) vInBankName.getTag()).getBankId(), mCurrentCollection.getAppCnlConfId(),
                        gatheringMoneyEt.getText().toString());
            }
        });
    }

    /**
     * 提现银行卡对话框
     */
    private void bankDialog(final boolean isOutBank) {
        View header = LayoutInflater.from(mContext).inflate(R.layout.layout_choose_bank_header, null);
        final DialogPlus dialog = DialogPlus.newDialog(this)
                .setAdapter(mBankAdapter)
                .setHeader(header)
                .setFooter(R.layout.layout_choose_bank_foot)
                .setGravity(Gravity.BOTTOM)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                        if (position < 0) return;
                        dialog.dismiss();
                        onDialogItemClickListener(isOutBank, position);
                    }
                })
                .setExpanded(false)
                .create();
        dialog.show();

        header.findViewById(R.id.arrow).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 选择银行卡列表点击事件处理
     */
    private void onDialogItemClickListener(boolean isOutBank, int position) {
        if ((isOutBank && mOutBankList.size() == position)
                || (!isOutBank && mInBankList.size() == position)) {
            ICardProvider provider = PublicProviderUtil.getProvider(ICardProvider.class);
            if (provider != null) {
                provider.openAddBankSetupActivity(mContext, false);
            }
            return;
        }
        try {
            BankInfoOutput checkBank;
            if (isOutBank) {
                checkBank = mOutBankList.get(position);
                showBankInfo(checkBank, true);
            } else {
                checkBank = mInBankList.get(position);
                showBankInfo(checkBank, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showBankInfo(BankInfoOutput infoOutput, boolean isOutBank) {
        try {
            JKImageLoader.getInstance().displayImage(mContext,
                    UrlConstants.getBaseUrl() + infoOutput.getLogoPath(), isOutBank ? vOutIcon : vInIcon);
            String bankNo = infoOutput.getBankNo();
            (isOutBank ? vOutBankName : vInBankName).setText(infoOutput.getBankName().replace(" ", "")
                    + "  (" + bankNo.substring(bankNo.length() - 4, bankNo.length()) + ")");
            (isOutBank ? vOutBankName : vInBankName).setTag(infoOutput);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setBankListData(List<BankInfoOutput> outBankList, List<BankInfoOutput> inBankList) {
        mOutBankList.clear();
        mInBankList.clear();
        if (outBankList != null) {
            mOutBankList.addAll(outBankList);
        }
        if (inBankList != null) {
            mInBankList.addAll(inBankList);
        }
        if (vInBankName.getTag() == null) {
            showBankInfo(mInBankList.get(0), false);
        }
    }

    @Override
    public void showListDataView(List<PayCollectionOutput> payListData) {
        if (payListData != null) {
            mPayListDatas.clear();
            mPayListDatas.addAll(payListData);
        }
        mPayAdapter.setNotifyData(mPayListDatas);
        if (mPayListDatas != null && mPayListDatas.size() > 0) {
            gatherListView.setVisibility(View.VISIBLE);
        } else {
            gatherListView.setVisibility(View.GONE);
        }
    }

    /**
     * 银行卡变更，重新请求
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshBankEvent event) {
        if (event != null) {
            mPresenter.selectUrmBankPage();
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return true;
    }

    @Override
    public void setPresenter(PersonalGatheringContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
